<?php if (!defined('CORE_DIR')) die('Wrong entry point!');

/* 
 * Copyright 2010 Anton Muraviev a.k.a kuromaisu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

// =============================================================================
// Section: MySQL Database Driver
// =============================================================================

Aero::import('db/base/driver');
Aero::import('db/mysql/result');

Aero::define('MysqlDriver', AS_CLASS);

/* -----------------------------------------------------------------------------
 * Class: MysqlDriver
 * -----------------------------------------------------------------------------
 *
 * MySQL-specific implementation of <AeroDatabase>.
 *
 */
class MysqlDriver extends AeroDatabase
{
	protected $quote_open = '`';
	protected $quote_close = '`';
	
	public function insertId()
	{
		return mysql_insert_id($this->connection);
	}
	
	public function affectedRows()
	{
		return mysql_affected_rows($this->connection);
	}
	
	public function escapeString($string)
	{
		return mysql_real_escape_string($string, $this->connection);
	}
	
	protected function _query($sql)
	{
		$ts = microtime(true);
		
		if (false === ($result = mysql_query($sql, $this->connection)))
		{
			throw new ErrorException(mysql_error($this->connection) . 
				'. Query: <code>' . $sql . '</code>', 0, E_USER_ERROR);
		}
		
		self::logQueryTime($sql,(microtime(true) - $ts));
		
		if (is_resource($result))
		{
			return new MysqlResult($result);
		}
		else
		{
			return $result;
		}
	}
	
	protected function _select($name)
	{
		if (!mysql_select_db($name,$this->connection))
		{
			throw new ErrorException(mysql_error($this->connection), 0, E_USER_ERROR);
		}

		self::$selected_database = $name;
	}
	
	protected function _connect($params)
	{
		$this->connection = (!empty($params['persistent'])) ?
			mysql_pconnect($params['server'],
				$params['username'],
				$params['password']) :
			mysql_connect($params['server'],
				$params['username'],
				$params['password']);

		if (!$this->connection)
		{
			throw new ErrorException(mysql_error(), 0, E_USER_ERROR);
		}
	}
}